import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_single_choice_button_widget/common_single_choice_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_choose_terminal_list/bean/company_choose_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_choose_terminal_list/company_choose_terminal_list_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';

class CheckTerminalSelectPage extends StatefulWidget {
  final List<CompanyChooseTerminalListItemBean> selectedList;
  const CheckTerminalSelectPage({Key key, this.selectedList}) : super(key: key);

  @override
  _CheckTerminalSelectPageState createState() => _CheckTerminalSelectPageState();
  ///跳转方法
  static Future<List<CompanyChooseTerminalListItemBean>> navigatorPush(
      BuildContext context,
      List<CompanyChooseTerminalListItemBean> selectedList) {
    return RouterUtils.routeForFutureResult<List<CompanyChooseTerminalListItemBean>>(
      context,
      CheckTerminalSelectPage(
        selectedList: selectedList,
      ),
    );
  }
}

class _CheckTerminalSelectPageState extends BasePagerState<CompanyChooseTerminalListItemBean,
    CheckTerminalSelectPage> {
  CompanyChooseTerminalListViewModel _viewModel;
  List<CompanyChooseTerminalListItemBean> _selectedList = [];
  @override
  void initState() {
    super.initState();
    _selectedList = widget.selectedList != null ? widget.selectedList : [];
    _viewModel = CompanyChooseTerminalListViewModel(this, () {
      return "";
    }, widget?.selectedList);
    _viewModel?.refresh();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF191E31),
      body: _toBodyWidget(),
    );
  }

  Widget _toBodyWidget(){
    return CommonPackUpKeyboardWidget(
      child: Column(
        children: [
          //表头
          _toTopBarWidget(),
          //搜索框
          _searchDepartmentWidget(),
          SizedBox(height: 10),
          Expanded(child: _toCustomListWidget()),
          _toHorizontalBar()
        ],
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "选择设备",
      // rightWidget: _buttonWidget(),
    );
  }

  Widget _searchDepartmentWidget() {
    return Container(
      height: 30,
      color: Color(0xFF3A3F50),
      child: CommonEditCallbackWidget(
        contentPadding: EdgeInsets.only(top: 0, bottom: 15),
        hintText: "搜索",
        customIcon: "images/common_search_ico.png",
        iconColor: Colors.white54,
        onChanged: (String dText) {
          _viewModel = CompanyChooseTerminalListViewModel(this, () {
            return dText;
          }, widget?.selectedList,);
          _viewModel?.refresh();
          setState(() { });
        },
      ),
    );
  }


  //封装的列表
  Widget _toCustomListWidget() {
    return VgPlaceHolderStatusWidget(
      errorOnClick: () => _viewModel?.refresh(),
      emptyOnClick: () => _viewModel?.refresh(),
      child: VgPullRefreshWidget.bind(
        state: this,
        viewModel: _viewModel,
        enablePullDown: false,
        child: ListView.separated(
            itemCount: data?.length ?? 0,
            padding: const EdgeInsets.all(0),
            physics: BouncingScrollPhysics(),
            keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
            itemBuilder: (BuildContext context, int index) {
              return _toListItemWidget(data?.elementAt(index), index);
            },
            separatorBuilder: (BuildContext context, int index) {
              return Container(
                height: 0.5,
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                padding: const EdgeInsets.only(left: 15),
                child: Container(
                  color: Color(0xFF303546),
                ),
              );}
        ),
      ),
    );
  }

  Widget _toListItemWidget(CompanyChooseTerminalListItemBean bean, int index) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () async {
        //判断字体是否选中
        if(bean?.selectStatus == CommonSingleChoiceStatus.selected){
          bean?.selectStatus = CommonSingleChoiceStatus.unSelect;
          _selectedList?.remove(bean);
        }else{
          _selectedList?.add(bean);
          bean?.selectStatus = CommonSingleChoiceStatus.selected;
        }
        setState(() {});
        VgToolUtils.removeAllFocus(context);
      },
      child: Container(
        color: Color(0xFF21263C),
        height: 50,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: [
            CommonSingleChoiceButtonWidget(bean?.selectStatus),
            // Padding(
            //   padding: const EdgeInsets.only(right: 10),
            //   child: CommonSingleChoiceButtonWidget(bean?.selectStatus),
            // ),
            SizedBox(width: 8,),
            Container(
              width: (VgToolUtils.getScreenWidth()/3)*2,
              child: Text(
                "${bean?.getTerminalName(index)}" ?? "",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Color(0xFFD0E0F7),
                  fontSize: 14,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toHorizontalBar(){
    return Container(
      height: 56,
      color: Color(0xFF3A3F50),
      // margin: const EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          SizedBox(width: 15,),
          GestureDetector(
            onTap: (){
              if(data==null){
                return;
              }
              if(data?.length != _selectedList?.length){
                data?.forEach((element) {
                  if(element?.selectStatus != CommonSingleChoiceStatus.selected){
                    element?.selectStatus = CommonSingleChoiceStatus.selected;
                    _selectedList.add(element);
                  }
                });
              }else{
                data?.forEach((element) {
                  element?.selectStatus = CommonSingleChoiceStatus.unSelect;
                  _selectedList.remove(element);
                });
              }
              setState(() { });
            },
            child: Text(
                ((_selectedList?.length??0) == (data?.length??0) && (_selectedList?.length??0)!=0)?"全不选" : "全选",
                style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 15)),
          ),
          SizedBox(width: 15,),
          Text(
              ((_selectedList?.length??0) != 0) ?"已选${_selectedList?.length ?? 0}设备" :"",
              style: TextStyle(color: Color(0xFF1890FF), fontSize: 12)),
          Spacer(),
          _buttonWidget(),
          SizedBox(width: 15,),
        ],
      ),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: true,
        width: 90,
        height: 36,
        unSelectBgColor:
        ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: ((_selectedList?.length??0) != 0)?VgColors.INPUT_BG_COLOR :VgColors.INPUT_BG_COLOR.withOpacity(0.5),
            fontSize: 15,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color:((_selectedList?.length??0) != 0) ?ThemeRepository.getInstance().getTextMainColor_D0E0F7() : ThemeRepository.getInstance().getTextMainColor_D0E0F7().withOpacity(0.5), fontSize: 15, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          //提交按钮
          if (_selectedList?.length != 0 && _selectedList != null) {
            _save();
          }
        },
      ),
    );
  }

  void _save() {
    List<CompanyChooseTerminalListItemBean> routerValue = [];
      _selectedList?.forEach((selectElement) {
        data?.forEach((element) {
          if(selectElement?.hsn?.contains(element?.hsn)){
            routerValue?.add(element);
          }
        });
    });
    RouterUtils.pop(context, result: routerValue);
  }
}
